package com.skyline.attraction.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.skyline.attraction.model.Attraction;
import com.skyline.attraction.model.AttractionFeature;
import com.skyline.attraction.service.AttractionFeatureService;
import com.skyline.attraction.service.AttractionService;
import com.skyline.base.controller.BaseController;
import com.skyline.base.exception.NoOperatePermissionException;
import com.skyline.base.exception.NoResourceException;
import com.skyline.base.exception.NotLoginException;
import com.skyline.base.type.Authority;
import com.skyline.common.bean.Page;
import com.skyline.common.util.Constant;
import com.skyline.common.util.ViewPaths;
import com.skyline.common.util.WebHelper;
import com.skyline.user.model.User;
import com.skyline.wo.model.Album;
import com.skyline.wo.model.Photo;

@RequestMapping("/attraction/feature")
@Controller
public class AttractionFeatureController extends BaseController {
	private static final Log LOGGER = LogFactory.getLog(AttractionFeatureController.class);
	@Autowired
	private AttractionFeatureService attractionFeatureService;
	@Autowired
	private AttractionService attractionService;

	private @Value("${attraction.listfeature.pagesize}")
	int listFeaturePageSize;

	@RequestMapping(value = "/list/{attractionId}", method = RequestMethod.GET)
	public ModelAndView listFeature(@PathVariable("attractionId") Long attractionId, Page page) {
		page.setSize(listFeaturePageSize);
		Attraction attraction = attractionService.getNormalAttraction(attractionId);
		List<AttractionFeature> featureList = attractionFeatureService.listFeatureByAttractionId(attractionId, page);
		ModelAndView view = new ModelAndView(ViewPaths.ATTRACTION_FEATURE_LIST);
		view.addObject("attraction", attraction);
		view.addObject("featureList", featureList);
		return view;

	}

	@RequestMapping(value = "/{featureId}", method = RequestMethod.GET)
	public ModelAndView viewFeature(@PathVariable("featureId") Long featureId) {
		Long viewerId = getViewerId();

		AttractionFeature feature = attractionFeatureService.getFeatureById(featureId);
		Long albumId = feature.getAlbumId();

		List<Photo> photos = albumService.listPhotoFilesOfAlbum(albumId, Authority.PUBLIC);

		ModelAndView view = new ModelAndView(ViewPaths.ATTRACTION_FEATURE_DETAIL);
		view.addObject("feature", feature);
		view.addObject("photos", photos);
		view.addObject("isAdmin", feature.getOwnerId().equals(viewerId));
		view.addObject("isCreator", feature.getCreatorId().equals(viewerId));
		return view;

	}

	@RequestMapping(value = "/add/{attractionId}", method = RequestMethod.GET)
	public ModelAndView addFeature(@PathVariable("attractionId") Long attractionId) {
		User user = checkAndReturnLoginedUser();

		Attraction attraction = attractionService.getNormalAttraction(attractionId);

		// List<AttractionFeature> featureList =
		// attractionFeatureService.listFeatureByAttractionId(attractionId,
		// null);

		ModelAndView view = new ModelAndView(ViewPaths.ATTRACTION_FEATURE_ADD);
		view.addObject("isAdmmin", user.getId().equals(attraction.getAdminId()));
		view.addObject("attraction", attraction);
		// view.addObject("featureList", featureList);
		return view;

	}

	@RequestMapping(value = "/add/{attractionId}", method = RequestMethod.POST)
	public ModelAndView addFeature(@PathVariable("attractionId") Long attractionId, AttractionFeature feature) {
		User user = checkAndReturnLoginedUser();

		String errMsg = validateForm("addFeatureForm", feature);
		if (errMsg != null) {
			return processValidationErrors("errMsg", errMsg, addFeature(attractionId));
		}

		Attraction attraction = attractionService.getNormalAttraction(attractionId);

		feature = attractionFeatureService.addFeature(feature, attraction, user);

		String url = buildRecirectPath("/attraction/feature/" + feature.getId() + "/bupload/" + feature.getAlbumId());
		return new ModelAndView(new RedirectView(url));
	}

	/**
	 * 打开上传图片到相册的页面
	 * 
	 * @param albumId
	 *            相册ID
	 * @param request
	 * */
	@RequestMapping(value = "/{featureId}/upload/{albumId}", method = RequestMethod.GET)
	public ModelAndView toUpload(@PathVariable("featureId") Long featureId, @PathVariable("albumId") Long albumId) {
		User user = checkAndReturnLoginedUser();

		AttractionFeature feature = attractionFeatureService.getFeatureById(featureId);

		checkModifyPermission(user, feature);

		Long attractionId = feature.getAttractionId();

		Album album = albumService.getAlbumForChange(albumId, attractionId);
		ModelAndView view = new ModelAndView(ViewPaths.ATTRACTION_FEATURE_TOUPLOAD);
		view.addObject("featureId", featureId);
		view.addObject("attractionId", attractionId);
		view.addObject("album", album);
		return view;
	}

	/**
	 * 打开上传图片到相册的页面
	 * 
	 * @param albumId
	 *            相册ID
	 * @param request
	 * */
	@RequestMapping(value = "/{featureId}/upload/{albumId}", method = RequestMethod.POST)
	public ModelAndView normalUpload(@PathVariable("featureId") Long featureId, @PathVariable("albumId") Long albumId,
			String submitToken, MultipartHttpServletRequest request) {
		User user = checkAndReturnLoginedUser();

		String errMsg = validateForm("normalUploadForm", submitToken);
		if (errMsg != null) {
			ModelAndView returnMav = toUpload(featureId, albumId);
			return processValidationErrors("errMsg", errMsg, returnMav);
		}

		AttractionFeature feature = attractionFeatureService.getFeatureById(featureId);

		checkModifyPermission(user, feature);

		Long attractionId = feature.getAttractionId();

		User userLiked = new User();
		userLiked.setId(attractionId);
		userLiked.setNickname(feature.getAttractionName());
		userLiked.setPortrait(feature.getAttractionPortrait());

		ModelAndView view = normalUpload(albumId, userLiked, request, ViewPaths.ATTRACTION_FEATURE_TOUPLOAD,
				ViewPaths.ATTRACTION_FEATURE_UPLOADOK);

		view.addObject("featureId", featureId);
		view.addObject("attractionId", attractionId);
		return view;
	}

	/**
	 * 打开批量上传图片到相册的页面
	 * 
	 * @param albumId
	 *            相册ID
	 * @param request
	 * */
	@RequestMapping(value = "/{featureId}/bupload/{albumId}", method = RequestMethod.GET)
	public ModelAndView btachUpload(@PathVariable("featureId") Long featureId, @PathVariable("albumId") Long albumId) {
		User user = checkAndReturnLoginedUser();

		AttractionFeature feature = attractionFeatureService.getFeatureById(featureId);

		checkModifyPermission(user, feature);

		Long attractionId = feature.getAttractionId();

		Album album = albumService.getAlbumForChange(albumId, attractionId);
		ModelAndView view = new ModelAndView(ViewPaths.ATTRACTION_FEATURE_UPLOADPHOTO);
		view.addObject("featureId", featureId);
		view.addObject("attractionId", attractionId);
		view.addObject("album", album);
		return view;
	}

	/**
	 * 批量上传压缩文件 用于attraction的特色图片上传
	 * 
	 * @param albumId
	 *            相册ID
	 * @param request
	 * */
	@RequestMapping(value = "/{featureId}/buploadok/{albumId}", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> batchUploadOk(@PathVariable("featureId") Long featureId, @PathVariable("albumId") Long albumId,
			@RequestParam("files") String files) {
		try {
			User user = checkAndReturnLoginedUser();
			AttractionFeature feature = attractionFeatureService.getFeatureById(featureId);

			checkModifyPermission(user, feature);

			User userLiked = new User();
			userLiked.setId(feature.getAttractionId());
			userLiked.setNickname(feature.getAttractionName());
			userLiked.setPortrait(feature.getAttractionPortrait());

			return batchUploadOk(albumId, files, userLiked);
		} catch (NotLoginException e) {
			return toJsonMap(false, "压缩图片必须登录", false);
		} catch (NoResourceException e) {
			LOGGER.warn("压缩图片失败，资源不存在", e);
			return toJsonMap(false, "没有找到对应景点或者相册，压缩图片失败！", true);
		} catch (NoOperatePermissionException e) {
			LOGGER.warn("压缩图片失败，无操作权限", e);
			return toJsonMap(false, "没有找到对应相册，压缩图片失败！", true);
		} catch (Exception e) {
			LOGGER.warn("压缩图片失败", e);
			return toJsonMap(false, "压缩图片失败！", true);
		}
	}

	/**
	 * 修改图片信息
	 * 
	 * @param albumId
	 *            相册ID
	 * @param request
	 * */
	@RequestMapping(value = "/uploadok/{featureId}/{albumId}", method = RequestMethod.GET)
	public ModelAndView uploadOk(@PathVariable("featureId") Long featureId, @PathVariable("albumId") Long albumId) {
		User user = checkAndReturnLoginedUser();

		AttractionFeature feature = attractionFeatureService.getFeatureById(featureId);

		checkModifyPermission(user, feature);

		Long attractionId = feature.getAttractionId();

		Album album = albumService.getAlbumForChange(albumId, attractionId);
		ModelAndView mav = new ModelAndView(ViewPaths.ATTRACTION_FEATURE_UPLOADOK);
		mav.addObject("album", album);
		mav.addObject("attractionId", attractionId);
		mav.addObject("featureId", featureId);
		return mav;
	}

	/**
	 * 用于attractionFeature的图片递交
	 * 
	 * @param albumId
	 *            相册ID
	 * @param request
	 * */
	@RequestMapping(value = "/uploadok/{featureId}/{albumId}", method = RequestMethod.POST)
	public ModelAndView uploadOk(@PathVariable("featureId") Long featureId, @PathVariable("albumId") Long albumId,
			String cover, String ext, @RequestParam("description") List<String> descriptions,
			@RequestParam("id") List<Long> ids, String submitToken) {
		User user = checkAndReturnLoginedUser();

		ModelAndView returnMav = null;
		String errMsg = validateForm("uploadOkForm", submitToken);
		if (errMsg != null) {
			returnMav = uploadOk(featureId, albumId);
			return processValidationErrors("errMsg", errMsg, returnMav);
		}

		int size = Math.min(ids.size(), descriptions.size());
		StringBuilder errMsgBuilder = new StringBuilder();
		for (int i = 0; i < size; i++) {
			if (ids.get(i) == null) {
				LOGGER.warn("操作失败，ID为:" + albumId + "的相册提交的第" + i + "张图片的ID为空");
			}
			errMsg = validateForm("descriptionOnlyForm", descriptions.get(i));
			if (errMsg != null) {
				if (returnMav == null) {
					returnMav = uploadOk(featureId, albumId);
				}
				errMsgBuilder.append("第").append(i + 1).append("张图片的").append(errMsg);
				return processValidationErrors("errMsg", errMsgBuilder.toString(), returnMav);
			}
		}

		AttractionFeature feature = attractionFeatureService.getFeatureById(featureId);

		checkModifyPermission(user, feature);

		Long attractionId = feature.getAttractionId();

		albumService.changePhotosDescription(albumId, ids, descriptions);
		albumService.changeAlbumCover(attractionId, albumId, cover, ext);

		if (StringUtils.hasLength(cover) && StringUtils.hasLength(ext)) {
			attractionFeatureService.updateFeaturePortrait(featureId, cover + "." + ext);
		}

		WebHelper.removeSessionAttribute(null, Constant.SESSION_UPLOAD_OK_FILES);

		String url = buildRecirectPath("/attraction/feature/" + featureId);
		ModelAndView mav = new ModelAndView(new RedirectView(url));
		return mav;
	}

//	/**
//	 * 用于删除attraction，feature的photo
//	 * 
//	 * @param ownerId
//	 * @param photoId
//	 * @return
//	 */
//	@RequestMapping(value = "/delphoto/{ownerId}/{photoId}", method = { RequestMethod.POST, RequestMethod.GET })
//	public ModelAndView deletePhoto(@PathVariable("ownerId") long ownerId, @PathVariable("photoId") long photoId) {
//
//		Long albumId = albumService.deletePhoto(ownerId, photoId);
//		String url = buildRecirectPath(ALBUM_URL_PREFIX + "/view/" + albumId);
//		ModelAndView mav = new ModelAndView(new RedirectView(url));
//		return mav;
//	}

	private void checkModifyPermission(User loginedUser, AttractionFeature destFeature) {
		Long userId = loginedUser.getId();
		Long adminId = destFeature.getOwnerId();
		Long creatorId = destFeature.getCreatorId();
		if (!userId.equals(adminId) && !userId.equals(creatorId)) {
			throw new NoOperatePermissionException("只有ID为[" + adminId + "]的管理员和ID为[" + creatorId + "]的创建者才能修改特色");
		}
	}
}
